package com.mgg.oss.util;

import java.io.InputStream;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSException;
import com.mgg.common.util.DateUtils;
import com.mgg.common.util.UUIDUtils;
import com.mgg.oss.properties.AliYunOSSProperties;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;


public class OSSUtils {

	private static String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";
	
	public static OSSClient getOSSClient(String accessKeyId, String accessKeySecret) {
		// endpoint以杭州为例，其它region请按实际情况填写
		// 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		
		return ossClient;
	}

	public static void upload(OSSClient ossClient, String bucketName, String ossKey, InputStream inputStream) {
		try {
			ObjectMetadata metadata = new ObjectMetadata();
			metadata.setCacheControl("no-cache");
			metadata.setHeader("Pragma", "no-cache");
			metadata.setContentEncoding("utf-8");
			ossClient.putObject(bucketName, ossKey, inputStream);
		} catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message: " + oe.getErrorCode());
            System.out.println("Error Code:       " + oe.getErrorCode());
            System.out.println("Request ID:      " + oe.getRequestId());
            System.out.println("Host ID:           " + oe.getHostId());
            throw new RuntimeException("图片上传失败");
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message: " + ce.getMessage());
            throw new RuntimeException("图片上传失败");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
	}

    public static void upload(AliYunOSSProperties aliYunOSSProperties, String ossKey, InputStream inputStream) {
        OSSClient ossClient = null;
        try {
            ossClient = new OSSClient(endpoint, aliYunOSSProperties.getAccessKeyId(), aliYunOSSProperties.getAccessKeySecret());
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setCacheControl("no-cache");
            metadata.setHeader("Pragma", "no-cache");
            metadata.setContentEncoding("utf-8");
            ossClient.putObject(aliYunOSSProperties.getBucketName(), ossKey, inputStream);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message: " + oe.getErrorCode());
            System.out.println("Error Code:       " + oe.getErrorCode());
            System.out.println("Request ID:      " + oe.getRequestId());
            System.out.println("Host ID:           " + oe.getHostId());
            throw new RuntimeException("图片上传失败");
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message: " + ce.getMessage());
            throw new RuntimeException("图片上传失败");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public static String upload(AliYunOSSProperties aliYunOSSProperties, String pathPrefix, String fileName, InputStream inputStream) {
        OSSClient ossClient = null;
        String result = null;
        try {
            ossClient = new OSSClient(endpoint, aliYunOSSProperties.getAccessKeyId(), aliYunOSSProperties.getAccessKeySecret());

            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setCacheControl("no-cache");
            metadata.setHeader("Pragma", "no-cache");
            metadata.setContentEncoding("utf-8");

            String path = pathPrefix + DateUtils.getDays() + "/";
            String ossKey = path + UUIDUtils.get32UUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
            PutObjectResult putObjectResult =  ossClient.putObject(aliYunOSSProperties.getBucketName(), ossKey, inputStream);
            result = aliYunOSSProperties.getDomain() + "/" + ossKey;
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message: " + oe.getErrorCode());
            System.out.println("Error Code:       " + oe.getErrorCode());
            System.out.println("Request ID:      " + oe.getRequestId());
            System.out.println("Host ID:           " + oe.getHostId());
            throw new RuntimeException("图片上传失败");
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message: " + ce.getMessage());
            throw new RuntimeException("图片上传失败");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return result;
    }
}
